/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.jbsc.commons.base.utils;

import org.apache.commons.lang3.StringUtils;
import org.jbase.jbsc.commons.core.vo.PagerVo;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Project: jbsc-commons <br/>
 * File: WebUtil.java <br/>
 * Class: org.jbase.jbsc.commons.base.utils.WebUtil <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: https://gitee.com/liuzp315 <br/>
 * Makedate: 2020/8/26 下午6:49 <br/>
 *
 * @author popo
 * @version 1.0
 * @since 1.0
 */
public abstract class WebUtil {
    /**
     * 描述 : 把请求参数转换成Map. <br/>
     * <p>
     *
     * @param request
     * @return
     */
    public static Map<String, Object> params(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<?> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            String parameter = request.getParameter(name);
            if (parameter != null)
                parameter = parameter.trim();
            params.put(name, parameter);
        }
        return params;
    }

    /**
     * 描述 : 把请求参数转换成Map. <br/>
     * <p>
     *
     * @param request
     * @return
     */
    public static Map<String, Object> queryParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<?> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            String parameter = request.getParameter(name);
            if (StringUtils.isBlank(parameter))
                continue;
            parameter = parameter.trim();
            params.put(name, parameter);
        }
        return params;
    }

    /**
     * 描述 : <描述函数实现的功能>. <br/>
     * <p>
     *
     * @param request
     * @param page
     */
    public static Map<String, Object> queryParams(HttpServletRequest request, PagerVo<?> page) {
        page.setCurrent(1);
        page.setSize(10);
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<?> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            String parameter = request.getParameter(name);
            if (StringUtils.isBlank(parameter))
                continue;
            parameter = parameter.trim();

            if (name.startsWith("_p_")) {
                if ("_p_size".equals(name)) {
                    page.setSize(Long.parseLong(parameter));
                } else if ("_p_no".equals(name)) {
                    page.setCurrent(Long.parseLong(parameter));
                }
            } else {
                params.put(name, parameter);
            }

        }
        return params;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getIp() {
        return getRequest().getRemoteHost();
    }

    /**
     * 获取所有请求的值
     */
    public static Map<String, String> getRequestParameters() {
        HashMap<String, String> values = new HashMap<>(20);
        HttpServletRequest request = getRequest();
        Enumeration enums = request.getParameterNames();
        while (enums.hasMoreElements()) {
            String paramName = (String) enums.nextElement();
            String paramValue = request.getParameter(paramName);
            values.put(paramName, paramValue);
        }
        return values;
    }

    /**
     * 获取 HttpServletRequest
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 获取 包装防Xss Sql注入的 HttpServletRequest
     *
     * @return request
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return new WafRequestWrapper(request);
    }

    public static String getToken() {
        return getRequest().getHeader("Authorization");
    }


    public static void trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
